package com.epfuse.cloud.common.redis.serializer.impl;

import com.epfuse.cloud.common.redis.serializer.AbstractRedisSerializer;
import com.epfuse.cloud.common.redis.serializer.annotation.EpfuseRedisSerializer;
import com.epfuse.cloud.common.redis.serializer.enums.SerializerType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.SerializationException;

import java.io.IOException;

/**
 * @ClassName Jackson2JsonSerializer
 * @Description TODO
 * @Author 孙峰
 * @Date 2023/3/8 10:29
 */
@EpfuseRedisSerializer(serializer = SerializerType.JACKSON)
public class Jackson2JsonSerializer extends AbstractRedisSerializer {


    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 序列化  空的字段也会序列化
     *
     * @param o object to serialize. Can be {@literal null}.
     * @return
     * @throws SerializationException
     */
    @Override
    public byte[] serialize(Object o) throws SerializationException {
        if (isEmpty(o)) {
            return EMPTY_ARRAY;
        }
        try {
            return objectMapper.writeValueAsBytes(o);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {

        if (isEmpty(bytes)) {
            return null;
        }
        try {
            return objectMapper.readValue(bytes, Object.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
